var Bind = require('./Bind');
var RUNTIME_NAMES = require('./StringEscape').RUNTIME_NAMES;
var expParser = require('./expParser');
var o = RUNTIME_NAMES.TOP_SCOPE + ',' + RUNTIME_NAMES.SUB_SCOPE + ',' + RUNTIME_NAMES.CALLER;
module.exports = {
    requireBlock: true,
    precompile: function (e, t, i) {
        if ('else' === e)
            return {
                s: [],
                d: 'true'
            };
        var n = t.match(/^\{\{(.+)\}\}$/);
        if (!n)
            throw new Error('Illegal expression is found in wx:' + e + '.');
        var a = expParser.parse(n[1]);
        var s = expParser.searchBindingPaths([a], i);
        return {
            s: [],
            d: 'function(' + o + '){return ' + expParser.stringify(a, i) + '}',
            b: s
        };
    },
    register: function (e, t, i) {
    },
    create: function (e, t, i, a, r, o, s, l, d, A, c) {
        var h = d.createVirtualNode('wx:' + e);
        h.__wxIfCondValue = true;
        h.__wxIfNextNode = null;
        h.__wxIfHasTrueCond = true;
        var u = null;
        if ('if' !== e) {
            'wx:if' !== (u = c.childNodes[c.childNodes.length - 1]).is && 'wx:elif' !== u.is ? u = null : u.__wxIfNextNode = h;
        };
        i.id && (h.id = i.id);
        var p = h.__wxIfUpdateNode = function () {
            var e = h.__wxIfCondValue;
            u && u.__wxIfHasTrueCond && (e = false);
            if (e && !h.childNodes.length) {
                var t = Bind.proxyTopScope(o);
                var c = Bind.proxySubScopes(s);
                h.__wxTopScope = t;
                h.__wxSubScopes = c;
                A(i.c, d, h, a, r, t, c, l);
            } else if (!e && h.childNodes.length) {
                for (var p in (Bind.removeBindingsForScope(h.__wxTopScope), h.__wxSubScopes))
                    Bind.removeBindingsForScope(h.__wxSubScopes[p]);
                for (; h.childNodes.length;)
                    h.removeChild(h.childNodes[0]);
            }
            h.__wxIfNextNode && h.__wxIfNextNode.__wxIfUpdateNode();
        };
        var g = function (e) {
            h.__wxIfCondValue = !!e;
            h.__wxIfHasTrueCond = h.__wxIfCondValue || u && u.__wxIfHasTrueCond;
            p();
        };
        if ('else' === e) {
            g(true);
        } else {
            Bind.addBindings(o, s, t.b, h, {
                e: t.d,
                o: function (e, t, i) {
                    g(i);
                }
            });
            g(t.d(a, r, null));
        }
        return h;
    }
};
